package com.sdx.console.atnm.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.atnm.entity.AtnmStatement;
import com.sdx.console.atnm.service.AtnmStatementService;
import com.sdx.console.base.entity.BaseUniv;
import com.sdx.console.base.service.BaseUnivService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 自荐信 接口
 */
@RequestMapping("/atnm/atnmStatement")
@Controller
public class AtnmStatementController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(AtnmStatementController.class);
    private static final String MODEL = "/atnm/atnmStatement";


    @Resource
	private AtnmStatementService atnmStatementService;

    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private BaseUnivService baseUnivService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("atnm.atnmStatement.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("atnm.atnmStatement.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer mainId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        AtnmStatement atnmStatement = atnmStatementService.queryById(mainId);
        view.addObject("atnmStatement", atnmStatement);
		setPageParam(view,request);
		try {
			view.addObject("atnmStatementJson", JacksonUtils.toJsonString(atnmStatement,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("atnm.atnmStatement.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("atnm.atnmStatement.query")
    @ResponseBody
    public JsonResult<PageQuery> list(AtnmStatement condtion)
    {
    	if (StringUtils.isNotEmpty(condtion.getHeadline())) {
    		condtion.setHeadline("%"+condtion.getHeadline()+"%");
	    }
	    if (StringUtils.isNotEmpty(condtion.getUnivName())) {
		    condtion.setUnivName("%"+condtion.getUnivName()+"%");
	    }
	    if (StringUtils.isNotEmpty(condtion.getMajorName())) {
		    condtion.setMajorName("%"+condtion.getMajorName()+"%");
	    }
        PageQuery page = condtion.getPageQuery();
        atnmStatementService.queryByCondition(page);
        return JsonResult.success(page);
    }

	@PostMapping("/univList.json")
	@Function("atnm.atnmStatement.query")
	@ResponseBody
	public List<BaseUniv> univList()
	{
		return atnmStatementService.selectUnivs();

	}

    private JsonResult save(boolean isNew,AtnmStatement atnmStatement,HttpServletRequest request
							,MultipartFile wordUrlFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/files/atnm/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(wordUrlFile)) {
			try
			{
		        String wordUrlFileNamePair = FileUtils.upload(subPath,wordUrlFile);
		        String wordUrlStoreFile = wordUrlFileNamePair.split("::")[0];
		        wordUrlStoreFile = subPath+wordUrlStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+wordUrlStoreFile,bucketName,wordUrlStoreFile.substring(1));
				String wordUrlUrl = "https://sdxcomm."+ ConfigService.ossDomain+wordUrlStoreFile;
				atnmStatement.setWordUrl(wordUrlUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,wordUrlStoreFile,wordUrlUrl,"f","自荐信");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);
		if (atnmStatement.getUnivId()!=null) {
			BaseUniv baseUniv = baseUnivService.queryById(atnmStatement.getUnivId());
			atnmStatement.setUnivName(baseUniv.getUnivName());
		}
    	if (isNew) {
			atnmStatement.setCreatedBy(user.getId().intValue());
			atnmStatement.setCreatedName(user.getName());
			atnmStatement.setCreatedTime(new Date());
			atnmStatement.setUpdatedBy(user.getId().intValue());
			atnmStatement.setUpdatedName(user.getName());
			atnmStatement.setUpdatedTime(new Date());
			atnmStatementService.save(atnmStatement);
		} else {
			atnmStatement.setUpdatedBy(user.getId().intValue());
			atnmStatement.setUpdatedName(user.getName());
			atnmStatement.setUpdatedTime(new Date());
			atnmStatementService.updateTemplate(atnmStatement);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("atnm.atnmStatement.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)AtnmStatement atnmStatement,HttpServletRequest request
							,@RequestParam("wordUrlFile") MultipartFile wordUrlFile
		)
    {

        return save(true,atnmStatement,request
					,wordUrlFile
		);
    }

    @PostMapping("/update.json")
    @Function("atnm.atnmStatement.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  AtnmStatement atnmStatement,HttpServletRequest request
							,@RequestParam("wordUrlFile") MultipartFile wordUrlFile
		) {
		return save(false,atnmStatement,request
		,wordUrlFile
		);
    }


   
    @GetMapping("/view.json")
    @Function("atnm.atnmStatement.query")
    @ResponseBody
    public JsonResult<AtnmStatement>queryInfo(Integer mainId) {
        AtnmStatement atnmStatement = atnmStatementService.queryById( mainId);
        return  JsonResult.success(atnmStatement);
    }

    @PostMapping("/delete.json")
    @Function("atnm.atnmStatement.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        atnmStatementService.batchDelAtnmStatement(idList);
        return JsonResult.success();
    }
    

}
